package cn.com.shopec.erp.product.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.com.shopec.erp.base.entity.SupplierInfo;
import cn.com.shopec.erp.base.service.ISupplierInfoService;
import cn.com.shopec.erp.base.vo.SupplierVo;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.excel.ExcelBaseImport;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.JsonHelper2;
import cn.com.shopec.erp.common.utils.LogicUtil;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConfig;
import cn.com.shopec.erp.product.commo.CommodityExcelExport;
import cn.com.shopec.erp.product.entity.Commodity;
import cn.com.shopec.erp.product.entity.ProdSupplier;
import cn.com.shopec.erp.product.service.ICatBrandService;
import cn.com.shopec.erp.product.service.ICommodityCatService;
import cn.com.shopec.erp.product.service.ICommodityService;
import cn.com.shopec.erp.product.service.IProdSupplierService;
import cn.com.shopec.erp.product.service.IProductService;
import cn.com.shopec.erp.product.vo.BrandVo;
import cn.com.shopec.erp.product.vo.CommodityCatVo;
import cn.com.shopec.erp.product.vo.CommodityVo;
import cn.com.shopec.erp.product.vo.ProdSupplierVo;
import cn.com.shopec.erp.product.vo.ProductVo1;
import cn.com.shopec.erp.stock.entity.ProductBarCode;
import cn.com.shopec.erp.stock.excel.impl.ProductBarCodeExcelImport;
import cn.com.shopec.erp.system.common.UserUtils;
import cn.com.shopec.erp.system.constant.SystemConstant;
import cn.com.shopec.erp.system.service.IUserService;
import cn.com.shopec.erp.system.vo.RoleVo;
import net.sf.json.JSONArray;

@Controller
@RequestMapping("/product/commoditymgt")
public class CommodityController {

    private static final Log log = LogFactory.getLog(CommodityController.class);

    @Resource
    private ICommodityService commodityService;

    @Resource
    private ISupplierInfoService supplierInfoService;

    @Resource
    private ICommodityCatService commodityCatService;

    @Resource
    private ICatBrandService catBrandService;

    @Resource
    private IProdSupplierService prodSupplierService;

    @Resource
    private IProductService productService;

    @Resource
    private IUserService userService;
    
    
    /**
     * 
     * @Title: toAddCommo
     * @Description: 跳转到新增商品页面
     * @param map
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-6-1下午04:45:32
     */
    @RequestMapping("/to_add_commo")
    public String toAddCommo(ModelMap map) {

        try {
            // 查询所有顶级分类
            CommodityCatVo catVo = new CommodityCatVo();
            catVo.setCatPno(SZSCMConstant.CAT_TOP_LEVEL);
            List<CommodityCatVo> catVolist = this.commodityCatService.getCommodityCatList(catVo);
            map.put("catVolist", catVolist);

        } catch (Exception e) {
            log.error("toAddCommo:" + e.getMessage(), e);
        }
        return "product/commo_add";
    }

    /**
     * 
     * @Title: addCommo
     * @Description: 添加商品信息
     * @param commodityVo
     * @param productString
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-6-3下午08:54:03
     */
    @RequestMapping("/add_commo")
    @ResponseBody
    public String addCommo(CommodityVo commodityVo, String productString) {

        try {
            this.commodityService.addCommoProdInfo(commodityVo, productString);

        } catch (Exception e) {

            log.error("addCommo:" + e.getMessage(), e);
            return SZSCMConstant.FAIL;
        }

        return SZSCMConstant.SUCCESS;

    }

    /**
     * 
     * @Title: listSupplierInfo
     * @Description: 跳转到货品供选择应商列表页面
     * @param supplierVo
     * @param map
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-5-31上午10:46:21
     */
    @RequestMapping("/to_list_select_supplier")
    public String toListSelectSupplier(SupplierVo supplierVo, String prodNo, String saleType, String salePrice,
            String prodRate,String brandNo, ModelMap map) {
        map.put("supplier", supplierVo);
        map.put("prodNo", prodNo);
        map.put("saleType", saleType);
        map.put("salePrice", salePrice);
        map.put("prodRate", prodRate);
        map.put("brandNo", brandNo);
        
        ProdSupplierVo psv = new ProdSupplierVo();
        psv.setProdNo(prodNo);
        List<ProdSupplier> list = this.prodSupplierService.getProdSupplierList(psv);
        map.put("list", JsonHelper2.toJson(list));
        return "product/supplier_select_list";
    }

    /**
     * 
     * @Title: listSelectSupplier
     * @Description: ajax分页查询供应商信息
     * @param supplierInfo
     * @param pageQuery
     * @param map
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-5-31上午10:56:00
     */
    @RequestMapping("/list_select_supplier")
    @ResponseBody
    public String listSelectSupplier(SupplierVo supplierVo, PageQuery pageQuery, ModelMap map) {
    	supplierVo.setState(SZSCMConstant.STATE_LOCK);
        PageFinder<SupplierInfo> selectSuppliers = this.supplierInfoService.querySupplier(supplierVo, pageQuery);
        map.put("Rows", selectSuppliers.getData());
        map.put("Total", selectSuppliers.getRowCount());

        return JsonHelper2.toJson(map);
    }

    /**
     * 
     * @Title: listSupplierInfo
     * @Description: 跳转到货品供选择应商列表页面
     * @param supplierVo
     * @param map
     * @return
     * @throws
     * @author: gaoyaxiong
     * @date: 2013-5-31上午10:46:21
     */
    @RequestMapping("/getToListSelectSupplier")
    public String getToListSelectSupplier(ProdSupplierVo prodSupplierVo, ModelMap map) {
    	if(StringUtil.isExist(prodSupplierVo.getProdNo())){
    		prodSupplierVo.setProdNo(prodSupplierVo.getProdNo().replace("'", ""));
    	}
    	prodSupplierVo.setProdNo(prodSupplierVo.getProdNo().replace("'", ""));
        map.put("prodSupplierVo", prodSupplierVo);
        return "product/prod_supplier_list";
    }

    /**
     * 
     * @Title: getAjaxPageFinderProdSupplier
     * @Description: ajax分页查询供应商价格信息
     * @param supplierInfo
     * @param pageQuery
     * @param map
     * @return
     * @throws
     * @author: gaoyaxiong
     * @date: 2013-5-31上午10:56:00
     */
    @RequestMapping("/getAjaxPageFinderProdSupplier")
    @ResponseBody
    public String getAjaxPageFinderProdSupplier(ProdSupplierVo prodSupplierVo, PageQuery pageQuery, ModelMap map) {
        PageFinder<ProdSupplierVo> ProdSupplierVos = this.prodSupplierService.getPageFinderProdSupplierST(prodSupplierVo,
                pageQuery);
        map.put("Rows", ProdSupplierVos.getData());
        map.put("Total", ProdSupplierVos.getRowCount());

        return JsonHelper2.toJson(map);
    }

    /**
     * 
     * @Title: listSelectSupplier
     * @Description: ajax分页查询供应商设置价格信息
     * @param supplierInfo
     * @param pageQuery
     * @param map
     * @return
     * @throws
     * @author: gaoyaxiong
     * @date: 2013-5-31上午10:56:00
     */
    @RequestMapping("/getAjaxSelectSupplier")
    @ResponseBody
    public String getAjaxSelectSupplier(SupplierInfo supplierInfo, PageQuery pageQuery, ModelMap map) {
        PageFinder<SupplierInfo> selectSuppliers = this.supplierInfoService.querySupplierInfos(supplierInfo, pageQuery);
        map.put("Rows", selectSuppliers.getData());
        map.put("Total", selectSuppliers.getRowCount());

        return JsonHelper2.toJson(map);
    }

    @RequestMapping("/list_product")
    public String listProuct(ModelMap map) {
        List<ProductVo1> products = this.commodityService.getProductList("e202b9facec044eca3976712cf34ba06");
        map.put("products", products);

        return "product/product_list";
    }

    /**
     * 
     * @Title: addSetProdSupplier
     * @Description:
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-5-31下午05:26:29
     */
    @RequestMapping("/add_set_prod_supplier")
    @ResponseBody
    public String addSetProdSupplier(String prodNo, String supplierList) {

        try {
            this.commodityService.addProdSupplier(prodNo, supplierList);
        } catch (Exception e) {
            log.error("addSetProdSupplier:" + e.getMessage(), e);
            return SZSCMConstant.FAIL;
        }

        return SZSCMConstant.SUCCESS;
    }

    /**
     * @Title: getAjaxNextCommodityCat
     * @Description: 获取分类
     * @param catVo
     * @param map
     * @return
     * @author: gaoyaxiong
     * @throws Exception
     * @date: 2013-5-27下午01:31:46
     */
    @RequestMapping("/getAjaxNextCommodityCat")
    @ResponseBody
    public void getAjaxNextCommodityCat(CommodityCatVo catVo, HttpServletResponse response) throws Exception {
        List<CommodityCatVo> list = this.commodityCatService.getCommodityCatList(catVo);
        if (LogicUtil.isNotNullAndEmpty(list)) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().append(JsonHelper2.toJson(list));
        }

    }

    /**
     * 
     * @Title: getBrandList
     * @Description: 根据分类查询所有的品牌
     * @param catNo
     * @param response
     * @throws
     * @author: duhui
     * @date: 2013-6-1下午04:27:33
     */
    @RequestMapping("/get_brand_list")
    @ResponseBody
    public void getBrandList(String catNo, HttpServletResponse response) {
        try {

            List<BrandVo> brandVoList = this.catBrandService.getBrand(catNo);

            if (LogicUtil.isNotNullAndEmpty(brandVoList)) {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().append(JsonHelper2.toJson(brandVoList));
            }

        } catch (Exception e) {
            log.error("getBrandList:" + e.getMessage(), e);
        }

    }

    /**
     * 跳转分页查询商品列表
     * 
     * @param commodity1
     * @param pageQuery
     * @param map
     * @return
     */
    @RequestMapping("toPageCommodityList")
    public String toPageCommodityList(CommodityVo commodityVo, PageQuery pageQuery, ModelMap map) throws Exception {
        List<RoleVo> roleVos = this.userService.getOwnRoleVos(UserUtils.getUserVo());
        map.put("roleVos", roleVos);

        map.put("commodity", commodityVo);
        return "/product/commodity_list";
    }

    /**
     * 分页查询商品列表
     * 
     * @param commodity1
     * @param pageQuery
     * @param map
     * @return
     */
    @RequestMapping({"aJaxPageCommodityList"})
    @ResponseBody
    public String aJaxPageCommodityList(CommodityVo commodityVo, PageQuery pageQuery, ModelMap map) {
    	JSONObject jsonObj = new JSONObject();
    	
    	try {
    	    PageFinder<CommodityVo> pageFinder = this.commodityService.pageFinderCommodity(commodityVo, pageQuery);
    	    jsonObj.put("Rows", pageFinder.getData());
    	    jsonObj.put("Total", pageFinder.getRowCount());
		} catch (Exception e) {
			log.error("aJaxPageCommodityList:"+e.getMessage());
		}
       
        return jsonObj.toJSONString();
    }

    /**
     * 根据商品编码删除数据，已通过审核数据不能删
     * 
     * @param commoNo
     * @return
     * @throws Exception
     */
    @RequestMapping("deleteCommodity")
    @ResponseBody
    public String deleteCommodity(String commoNo) throws Exception {

        if (LogicUtil.isNotNullAndEmpty(commoNo)) {
            Commodity com = this.commodityService.getCommodityByCommoNo(commoNo);
            if (com.getCheckState() == 1) {// 已审核
                return "check";
            } else {
                this.commodityService.delCommodity(commoNo);
                return SZSCMConstant.SUCCESS;
            }
        }
        return SZSCMConstant.FAIL;
    }

    /**
     * @Title: showCommodityDetail
     * @Description: 商品审核
     * @param commoNo
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     */
    @RequestMapping("showCommodityInfo")
    public ModelAndView showCommodityInfo(String commoNo, String type, ModelMap modelMap) throws Exception {
        List<RoleVo> roleVos = this.userService.getOwnRoleVos(UserUtils.getUserVo());
        modelMap.put("roleVos", roleVos);

        CommodityVo commo = this.commodityService.getCommodity(commoNo);
        modelMap.put("commodity", commo);
        modelMap.put("type", type);

        return new ModelAndView("/product/commodity_info");
    }
    
    /**
     * @Title: showCommodityDetail
     * @Description: 商品明细
     * @param commoNo
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     */
    @RequestMapping("showCommodityInfoList")
    public ModelAndView showCommodityInfoList(String commoNo, String type, ModelMap modelMap) throws Exception {
        List<RoleVo> roleVos = this.userService.getOwnRoleVos(UserUtils.getUserVo());
        modelMap.put("roleVos", roleVos);

        CommodityVo commo = this.commodityService.getCommodity(commoNo);
        modelMap.put("commodity", commo);
        modelMap.put("type", type);

        return new ModelAndView("/product/commodity_infoList");
    }

    /**
     * @Title: ajaxToProdList
     * @Description: ajax方式，根据商品号取货品列表
     * @param commoNo
     * @param pageQuery
     * @param map
     * @return
     * @throws
     * @author: lule
     * @date: 2013-6-1下午6:17:20
     */
    @RequestMapping("ajaxToProdList")
    @ResponseBody
    public String ajaxToProdList(String commoNo, PageQuery pageQuery, ModelMap map) {

        JSONObject jsonObj = new JSONObject();
        try {
            PageFinder<ProductVo1> pageFinder = this.productService.getPagedProductListByCommoNo(commoNo, pageQuery);

            jsonObj.put("Rows", pageFinder.getData());
            jsonObj.put("Total", pageFinder.getRowCount());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return jsonObj.toJSONString();
    }

    /**
     * @Title: checkCommodity
     * @Description: 审核商品
     * @param commoNo
     * @param checkState
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-6-1下午7:05:38
     */
    @RequestMapping("checkCommodity")
    @ResponseBody
    public String checkCommodity(String commoNo, int checkState, ModelMap modelMap) throws Exception {
        String resMsg = SZSCMConstant.FAIL;
        try {
            int res = this.commodityService.checkCommodity(commoNo, checkState);
            switch (res) {
            case SZSCMConstant.SUCCESS_INT:
                resMsg = SZSCMConstant.SUCCESS;
                break;
            case -1:
                resMsg = "操作失败，提交的审核结果不正确";
                break;
            case -2:
                resMsg = "操作失败，无法根据提交的参数找到对应的商品";
                break;
            case -3:
                resMsg = "商品资料同步失败!";
                break;
            default:
                ;
            }
        } catch (Exception e) {
            log.error("checkCommodity：" + e.getMessage(), e);
        }

        return resMsg;
    }

    /**
     * 
     * @Title: toUpdateCommo
     * @Description: 跳转到修改商品页面
     * @param map
     * @return
     * @throws Exception
     * @throws
     * @author: duhui
     * @date: 2013-6-1下午04:45:32
     */
    @RequestMapping("/to_update_commo")
    public String toUpdateCommo(String commoNo, ModelMap map) throws Exception {
        CommodityVo cvo = this.commodityService.getCommodity(commoNo);
        List<ProductVo1> prolist = this.commodityService.getProductList(commoNo);
        map.put("prolist", prolist);
        map.put("commodityVo", cvo);
        return "product/commo_update";
    }

    /**
     * 获取商品中的货品
     * 
     * @param commoNo
     * @param response
     *            gaoyaxiong 2013-6-6 16:46:23
     */
    @RequestMapping("getProductVos")
    @ResponseBody
    public void getProductVos(String commoNo, HttpServletResponse response) {
        try {
            List<ProductVo1> prolist = this.commodityService.getProductList(commoNo);

            if (LogicUtil.isNotNullAndEmpty(prolist)) {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().append(JsonHelper2.toJson(prolist));
            }

        } catch (Exception e) {

        }
    }

    /**
     * 
     * @Title: updateCommo
     * @Description: 修改商品信息
     * @param commodityVo
     * @param productString
     * @return
     * @throws
     * @author: gaoyaxiong
     * @date: 2013-6-5下午08:54:03
     */
    @RequestMapping("/update_commo")
    @ResponseBody
    public String updateCommo(CommodityVo commodityVo, String productString, String delProdNo) {
        try {
            if (StringUtil.isExist(delProdNo)) {
                JSONArray jsonArray = JSONArray.fromObject(delProdNo);
                if (jsonArray != null && jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        net.sf.json.JSONObject jsonJ = jsonArray.getJSONObject(i);
                        if (jsonJ != null && jsonJ.get("prodNo")!= null) {
                            this.productService.delProduct(jsonJ.getString("prodNo"));

                        }
                    }
                }
            }
            return this.commodityService.updateCommoProdInfo(commodityVo, productString);
        } catch (Exception e) {
            log.error("updateCommo：" + e.getMessage(), e);
            return SZSCMConstant.FAIL;
        }
    }

    /**
     * 判断货品是否设置供应商价格
     * 
     * @param commoNo
     * @return
     */
    @RequestMapping("getIsSetSupplier")
    @ResponseBody
    public String getIsSetSupplier(String commoNo) {
        List<ProductVo1> prolist = this.commodityService.getProductList(commoNo);
        String erProd = "";
        for (ProductVo1 productVo : prolist) {
            ProdSupplierVo prodSupplierVo = new ProdSupplierVo();
            prodSupplierVo.setProdNo(productVo.getProdNo());
            List<ProdSupplier> list = new ArrayList<ProdSupplier>();
            list = this.prodSupplierService.getProdSupplierList(prodSupplierVo);
            if (list == null || list.size() == 0) {
                if (erProd != "") {
                    erProd += ",";
                }
                erProd += productVo.getProdBarCode();
            }
        }
        return erProd;

    }

    /**
     * 
     * @Title: validationRepeatProdBarCode
     * @Description: 验证是否有重复的货品条码
     * @param prodBarCode
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-6-13下午02:29:24
     */
    @RequestMapping("/validationRepeatProdBarCode")
    @ResponseBody
    public String validationRepeatProdBarCode(String prodBarCode) {

        return this.productService.validationRepeatProdBarCode(prodBarCode);
    }

    /**
     * 
     * @Title: toCheckNopass
     * @Description: 跳转到商品审核不通过的描述页面
     * @param commoNo
     * @param checkState
     * @param map
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-6-29上午10:32:24
     */
    @RequestMapping("/to_check_nopass")
    public String toCheckNopass(String commoNo, int checkState, ModelMap map) {
        map.put("commoNo", commoNo);
        map.put("checkState", checkState);

        return "product/check_nopass";
    }

    /**
     * 
     * @Title: checknopass
     * @Description: 审核不通过的操作
     * @return
     * @throws
     * @author: duhui
     * @date: 2013-6-28上午11:06:30
     */
    @RequestMapping("/check_nopass")
    @ResponseBody
    public String checknopass(String commoNo, int checkState, String desc) {
        String result = SZSCMConstant.FAIL;

        try {
            result = this.commodityService.checkNoCommodity(commoNo, checkState, desc);
        } catch (Exception e) {
            log.error("checknopass:" + e.getMessage());
            result = SZSCMConstant.FAIL;
        }

        return result;
    }
    
    
    /**
     * 
     * @Title: doExportExcel
     * @Description: 导出商品信息
     * @return
     * @throws IOException 
     * @throws
     * @author: gaoyaxinog
     * @date: 2013-7-25 17:46:30
     */
    @RequestMapping("/doExportExcel")
    public String doExportExcel(CommodityVo commodityVo,HttpServletResponse response) throws IOException{
    	commodityVo.setCommoNo(URLDecoder.decode(commodityVo.getCommoNo(), SystemConstant.CHARSET_UTF8));
    	commodityVo.setProdNo(URLDecoder.decode(commodityVo.getProdNo(), SystemConstant.CHARSET_UTF8));
    	commodityVo.setCommoName(URLDecoder.decode(commodityVo.getCommoName(), SystemConstant.CHARSET_UTF8));
    	String tName=DateUtil.parseDate(new Date(), "yyyyMMddHHmmss");
		response.addHeader("content-disposition", "attachment;filename=product"+tName+".xls" ); 
		response.setContentType("application/vnd.ms-excel");
		
    	List list = this.commodityService.getCommodityDetail(commodityVo);
    	String[] title = {"商品编号","商品名称","分类名称","品牌名称","商品类型","创建时间","商品描述","货品编号","货品条码","销售类型","库存类型","含税零售价","税率(%)","未税零售价","最低订货数量","箱包装规格","单位","规格","供应商名称","供应商编号","未税成本价","含税成本价","毛利率(%)","是否可退货"};
    	CommodityExcelExport excelExport = new CommodityExcelExport();
    	excelExport.createCollectSheet(list, title, response.getOutputStream());
		return null;
    }
    
    /**
     * 导入商品和货品信息
     * @param productBarCode
     * @param barCodeFile
     * @return
     */
    @RequestMapping("/importBarCode")
	@ResponseBody
	public String fileUpload(ProductBarCode productBarCode, @RequestParam MultipartFile barCodeFile) {
		if (!barCodeFile.isEmpty()) {
			try {
				ExcelBaseImport loadExcel = new ProductBarCodeExcelImport(barCodeFile.getInputStream(),barCodeFile.getOriginalFilename(), 1);
				List<List<Object>> excelData = loadExcel.getObjectList();
				if (excelData != null) {
					String result = commodityService.importProductBarCodes( excelData);
					if(result.equals("") || result==null){
						return SZSCMConstant.SUCCESS;
					}
					else{
						return result;
					}
				}
			} catch (Exception e) {
				log.error("importFile" + e.getMessage(), e);
			}
		}
	 return SZSCMConstant.FAIL;
	}
    
    /***
     * 下载导入货品模板
     * @param response
     */
    @RequestMapping("downloadTemplet")
	public void downloadTemplet(HttpServletResponse response) {
		try {
			String configPath = MultiChannelConfig.class.getClassLoader().getResource("/").getPath();
			configPath = java.net.URLDecoder.decode(configPath, "utf-8");
			InputStream inStream = new FileInputStream(configPath + "bulkInsertMerchandise.xlsx");// 文件的存放路径
			response.reset();
			response.setContentType("bin");
			response.addHeader("Content-Disposition",
					"attachment;filename=" + URLEncoder.encode("批量导入商品模板.xlsx", "UTF-8"));
			byte[] b = new byte[100];
			int len;
			while ((len = inStream.read(b)) > 0)
				response.getOutputStream().write(b, 0, len);
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    
}